//
//  MyJourneyViewController.m
//  TravelFollowYourHeart
//
//  Created by appleLJ on 2017/12/13.
//  Copyright © 2017年 Lwx. All rights reserved.
//

#import "MyJourneyViewController.h"
#import "MyJourneyTableViewCell.h"
#import "MyJourneyModel.h"
//#import "LoginViewController.h"
#import "XXTripTableViewController.h"
#import "CityListViewController.h"
#import "RadioButton.h"
//#import "ChooseJourneyViewController.h"
#import "MineViewController.h"
@interface MyJourneyViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) UIView *headerView;//头试图
@property(nonatomic,strong) UIView *footerView;//尾试图
@property(nonatomic,strong) NSMutableArray *dataArray;//数据源
@property(nonatomic, strong)MyJourneyModel *model;
@property(nonatomic, strong)MyJourneyModelData * modelData;
@property(nonatomic, assign)int trip_id;
@property(nonatomic, strong)UIView * addToTheDayBG;
@property(nonatomic, assign)int travelDays;
@property(nonatomic, strong)NSArray * daysArr;
@property(nonatomic, strong)NSArray * tripDaysArr;//显示几个button
@property(nonatomic, assign)int addToTheDayth;//加入行程到第几天
@property(nonatomic, strong)UIViewController * lastVC;
@end

@implementation MyJourneyViewController (Networking)
//得到行程数据
- (void)getMyJourneyTableList{
//    if ([UserModel isSaveLogin]) {
        NSDictionary * dic = @{
                               @"mid":[UserModel intance].member_id,
                               @"token":[UserModel intance].token
                               };
        WS(ws)
        [[HUDHelper sharedInstance]syncLoading:@"翻箱中..."];
        [[HttpRequest shardWebUtil] postNetworkRequestURLString:Url(@"/member/myTrip") andParas:dic andTransferGottenData:^(id obj, NSError *error) {
            [[HUDHelper sharedInstance]syncStopLoading];
            if (error){
                [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
            }else{
                if ([obj[@"code"] integerValue] == 100000){
                    [self.dataArray removeAllObjects];
                    ws.model = [MyJourneyModel yy_modelWithDictionary:obj];
                    [self.dataArray addObjectsFromArray:ws.model.data];
                    [self.tableView reloadData];
                }else{
                    [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
                }
            }
        }];
}
//删除行程
- (void)deleteJourneyDataWithTrip_id:(int)trip_id{
    NSDictionary * dic = @{
                           @"mid":[UserModel intance].member_id,
                           @"token":[UserModel intance].token,
                           @"trip_id":@(trip_id)
                           };
//    WS(ws)
    [[HUDHelper sharedInstance]syncLoading:@"翻箱中..."];
    [[HttpRequest shardWebUtil] postNetworkRequestURLString:Url(@"/member/delTrip") andParas:dic andTransferGottenData:^(id obj, NSError *error) {
        [[HUDHelper sharedInstance]syncStopLoading];
        if (error){
            [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
        }else{
            if ([obj[@"code"] integerValue] == 100000){
                [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
            }else{
                [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
            }
        }
    }];
}
//修改行程名称
- (void)changeJourneyNameWithTrip_id:(int)trip_id withName:(NSString *)name{
    NSDictionary * dic = @{
                           @"mid":[UserModel intance].member_id,
                           @"token":[UserModel intance].token,
                           @"trip_id":@(trip_id),
                           @"name":name
                           };
//    WS(ws)
    [[HUDHelper sharedInstance]syncLoading:@"翻箱中..."];
    [[HttpRequest shardWebUtil] postNetworkRequestURLString:Url(@"/member/editTrip") andParas:dic andTransferGottenData:^(id obj, NSError *error) {
        [[HUDHelper sharedInstance]syncStopLoading];
        if (error)
        {
            [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
        }
        else
        {
            if ([obj[@"code"] integerValue] == 100000)
            {
                
                [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
            }
            else
            {
                [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
            }
        }
    }];
}

- (void)addTripToTheDay{
    NSDictionary * dic = @{
                           @"mid":[UserModel intance].member_id,
                           @"token":[UserModel intance].token
                           };
    WS(ws)
    [[HUDHelper sharedInstance]syncLoading:@"翻箱中..."];
    [[HttpRequest shardWebUtil] postNetworkRequestURLString:Url(@"/member/myTrip") andParas:dic andTransferGottenData:^(id obj, NSError *error) {
        [[HUDHelper sharedInstance]syncStopLoading];
        if (error){
            [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
        }else{
            if ([obj[@"code"] integerValue] == 100000){
                ws.model = [MyJourneyModel yy_modelWithDictionary:obj];
            }else{
                [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
            }
        }
    }];
}
//确定之后加入的行程
- (void)addTrip{
    NSDictionary * dic = @{
                           @"trip_id":@(self.trip_id),
                           @"token":[UserModel intance].token,
                           @"mid":[UserModel intance].member_id,
                           @"tid":@(self.tid),
                           @"day":@(self.addToTheDayth)
                           };
    [[HttpRequest shardWebUtil] postNetworkRequestURLString:Url(@"/index/addOneday") andParas:dic andTransferGottenData:^(id obj, NSError *error) {
        if (error) {
            [[HUDHelper sharedInstance] tipMessage:obj[@"msg"]];
        }else{
            if ([obj[@"code"] integerValue] == 100000){

            }else{
                [[HUDHelper sharedInstance] tipMessage:obj[@"msg"]];
            }
        }
    }];
}

@end

@implementation MyJourneyViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationItem.title = @"我的行程";
    [self getMyJourneyTableList];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = getColor(whiteColor);
    [self.view addSubview:self.tableView];
    self.daysArr = @[@"第一天", @"第二天", @"第三天"];
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"新建" style:(UIBarButtonItemStylePlain) target:self action:@selector(rightBtnEvent)];
    self.navigationItem.rightBarButtonItem = rightButton;
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:getColor(mainColor), NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];
    
}

#pragma mark -- event

- (void)rightBtnEvent{
    NSLog(@"新建");
    CityListViewController * cityListVC = [[CityListViewController alloc] init];
    [self.navigationController pushViewController:cityListVC animated:YES];
}

- (void)tapAction:(UITapGestureRecognizer *)tap{
    NSLog(@"执行");
    self.addToTheDayth = 0;
    self.addToTheDayBG.hidden = YES;
}
#pragma mark -- UITableViewDelegate & UITableViewDataSource
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *vcsArray = [self.navigationController viewControllers];
    NSInteger vcCount = vcsArray.count;
    _lastVC = vcsArray[vcCount-2];
    
    if ([_lastVC isKindOfClass:[MineViewController class]]) {
        
        MyJourneyTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        XXTripTableViewController * tripTableVC = [[XXTripTableViewController alloc] init];
        tripTableVC.trip_id = [cell.modelData.userId intValue];
        [self.navigationController pushViewController:tripTableVC animated:YES];
        
    }else{
        
        [self addTripToTheDay];
        [self.view addSubview:self.addToTheDayBG];
        self.modelData = self.dataArray[indexPath.row];
        if ([self.modelData.day isEqualToString:@"1"]) {
            self.travelDays = 1;
        }
        if ([self.modelData.day isEqualToString:@"2"]) {
            self.travelDays = 2;
        }
        if ([self.modelData.day isEqualToString:@"3"]) {
            self.travelDays = 3;
        }
        [self addBGView];
        self.addToTheDayBG.hidden = NO;
        
        MyJourneyTableViewCell * cell = [self.tableView cellForRowAtIndexPath:indexPath];
        cell.modelData = self.dataArray[indexPath.row];
        self.trip_id = [cell.modelData.userId intValue];
        NSLog(@"%i",self.trip_id);
        
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyJourneyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MyJourneyTableViewCell class]) forIndexPath:indexPath];
    cell.modelData = self.dataArray[indexPath.row];
    cell.editHandle = ^{
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请编辑行程名称" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
            textField.placeholder = @"name";
            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
            textField.borderStyle = UITextBorderStyleRoundedRect;
        }];
        WS(ws)
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            //改名事件
            for(UITextField *text in alertController.textFields){
                NSLog(@"text = %@", text.text);
                ws.modelData = ws.dataArray[indexPath.row];
                ws.trip_id = [self.modelData.userId intValue];
                [ws changeJourneyNameWithTrip_id:self.trip_id withName:text.text];
                ws.modelData.name = text.text;
            }
            [ws.tableView reloadData];

        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    };
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44 / WIDTH_5S_SCALE;
}

//侧滑删除
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
//进入编辑模式，按下出现的编辑按钮后
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView setEditing:NO animated:YES];
    MyJourneyTableViewCell * cell = [self.tableView cellForRowAtIndexPath:indexPath];
    cell.modelData = self.dataArray[indexPath.row];
    self.trip_id = [cell.modelData.userId intValue];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"你确定删除该消息？" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        WS(ws)
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            //删除事件
            [ws.dataArray removeObjectAtIndex:indexPath.row];
            [ws deleteJourneyDataWithTrip_id:self.trip_id];
            [ws.tableView reloadData];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}
//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}
//设置进入编辑状态时，Cell不会缩进
- (BOOL)tableView: (UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

#pragma mark -- init
- (UIView *)addToTheDayBG{
    if (!_addToTheDayBG) {
        //透明背景
        _addToTheDayBG = [[UIView alloc] init];
        _addToTheDayBG.frame = CGRectMake(0, 0, self.view.width, self.view.height);
        _addToTheDayBG.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.4];
        UITapGestureRecognizer *tapGesturRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
        [_addToTheDayBG addGestureRecognizer:tapGesturRecognizer];
        _addToTheDayBG.hidden = YES;
        
    }return _addToTheDayBG;
}

- (void)addBGView{
    //按钮背景
    UIView * squareBGView = [[UIView alloc] init];
    int squareBGViewH = 160/WIDTH_5S_SCALE;
    int squareBGViewW = 10/WIDTH_5S_SCALE;
    squareBGView.frame = CGRectMake(squareBGViewW, self.view.centerY - squareBGViewH/2-64, self.view.width - 2*squareBGViewW, squareBGViewH);
    squareBGView.backgroundColor = [UIColor whiteColor];
    squareBGView.layer.cornerRadius = 8;
    squareBGView.layer.masksToBounds = YES;
    [_addToTheDayBG addSubview:squareBGView];
    
    //标题
    int titleLabH = 20/WIDTH_5S_SCALE;
    UILabel * titleLab = [[UILabel alloc] init];
    titleLab.text = @"请选择加入到行程第几天";
    titleLab.frame = CGRectMake(0, titleLabH/2, squareBGView.width, titleLabH);
    titleLab.font = DEF_FontSize_14;
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.textColor = getColor(mainColor);
    [squareBGView addSubview:titleLab];
    
    //选择天数按钮
    int radioBtnH = 30/WIDTH_5S_SCALE;
    NSMutableArray* buttonsArray = [NSMutableArray arrayWithCapacity:3];
    CGRect btnRect = CGRectMake(squareBGViewW, radioBtnH, squareBGView.width - 2*squareBGViewW, radioBtnH);
    self.tripDaysArr = [self.daysArr subarrayWithRange:NSMakeRange(0, self.travelDays)];
    for (NSString* optionTitle in self.tripDaysArr) {
        RadioButton* btn = [[RadioButton alloc] initWithFrame:btnRect];
        [btn addTarget:self action:@selector(onRadioButtonValueChanged:) forControlEvents:UIControlEventTouchUpInside];
        btnRect.origin.y += 30;
        [btn setTitle:optionTitle forState:UIControlStateNormal];
        [btn setTitleColor:getColor(mainColor) forState:UIControlStateNormal];
        btn.titleLabel.font = DEF_FontSize_14;
        [btn setImage:[UIImage imageNamed:@"unSelect"] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"select"] forState:UIControlStateSelected];
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, 6, 0, 0);
        [squareBGView addSubview:btn];
        [buttonsArray addObject:btn];
    }
    [buttonsArray[0] setGroupButtons:buttonsArray]; // 把按钮放进群组中
    
    int bottomBtnX = 20/WIDTH_5S_SCALE;
    int bottomBtnW = 40/WIDTH_5S_SCALE;
    int bottomBtnH = 20/WIDTH_5S_SCALE;
    UIButton * sureBtn = [[UIButton alloc] initWithFrame:CGRectMake(bottomBtnX, titleLab.bottom + 3*radioBtnH + 10, bottomBtnW, bottomBtnH)];
    [squareBGView addSubview:sureBtn];
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    sureBtn.titleLabel.font = DEF_FontSize_14;
    [sureBtn setBackgroundColor:[UIColor whiteColor]];
    [sureBtn setTitleColor:getColor(mainColor) forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(sureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(squareBGView.width - bottomBtnX - sureBtn.width, sureBtn.top, sureBtn.width, sureBtn.height)];
    [squareBGView addSubview:cancelBtn];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = DEF_FontSize_14;
    [cancelBtn setBackgroundColor:[UIColor whiteColor]];
    [cancelBtn setTitleColor:getColor(mainColor) forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
}

- (void)sureBtnClick{
    NSLog(@"确定");
    if (self.addToTheDayth == 0) {
        [[HUDHelper sharedInstance]tipMessage:@"请选择加入第几天的行程中"];
    }else{
        [self addTrip];
        XXTripTableViewController * tripTableVC = [[XXTripTableViewController alloc] init];
        tripTableVC.trip_id = self.trip_id;
        NSLog(@"%i",self.trip_id);
        [self.navigationController pushViewController:tripTableVC animated:YES];
    }
}

- (void)cancelBtnClick{
    self.addToTheDayth = 0;
    self.addToTheDayBG.hidden = YES;
}

- (void)onRadioButtonValueChanged:(RadioButton *)sender{
    NSLog(@"%@",sender.titleLabel.text);
    if ([sender.titleLabel.text isEqualToString:@"第一天"]) {
        self.addToTheDayth = 1;
    }
    if ([sender.titleLabel.text isEqualToString:@"第二天"]) {
        self.addToTheDayth = 2;
    }
    if ([sender.titleLabel.text isEqualToString:@"第三天"]) {
        self.addToTheDayth = 3;
    }
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 49) style:UITableViewStylePlain];
        _tableView.backgroundColor = getColor(whiteColor);
        _tableView.separatorInset = UIEdgeInsetsZero;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableHeaderView = self.headerView;
        _tableView.tableFooterView = self.footerView;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        [_tableView registerClass:[MyJourneyTableViewCell class] forCellReuseIdentifier:NSStringFromClass([MyJourneyTableViewCell class])];
    }
    return _tableView;
}

- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.01)];
    }
    return _headerView;
}

- (UIView *)footerView{
    if (!_footerView) {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.01)];
    }
    return _footerView;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = @[
                       ].mutableCopy;
    }
    return _dataArray;
}

@end
